<template>
  <div class="booking-container">
    <div class="header-panel">
        <h2>预订会议室</h2>
        <button @click="router.push('/orders')" class="my-btn">查看我的订单</button>
    </div>
    <div class="search-panel">
      <label>会议开始时间：</label>
      <input 
        type="datetime-local" 
        v-model="search.startTime" 
        :min="minDateTime"
        :max="maxDateTime"
        step="3600" 
        required 
        />
      
      <label>会议结束时间：</label>
      <input 
        type="datetime-local" 
        v-model="search.endTime" 
        :min="minDateTime"
        :max="maxDateTime"
        step="3600" 
        required 
        />

      <label>参会人数：</label>
      <input type="number" v-model.number="search.participantNum" min="1" required />

      <label>所需设备：</label>
      <div class="device-check">
        <input type="checkbox" id="projector" v-model="search.hasProjector" />
        <label for="projector">投影仪</label>

        <input type="checkbox" id="sound" v-model="search.hasSound" />
        <label for="sound">音响</label>

        <input type="checkbox" id="internet" v-model="search.hasInternet" />
        <label for="internet">网络</label>
      </div>

      <button @click="filterRooms">搜索可用会议室</button>
    </div>

    <div class="room-list">
      <div v-for="room in rooms" :key="room.id" class="room-card">
        <h3>{{ room.room_name }}</h3>
        <p>类型：{{ room.room_type }}</p>
        <p>座位数：{{ room.seat_count }}人</p>
        <p>设备：
          <span v-if="room.has_projector">投影仪</span>
          <span v-if="room.has_sound">&nbsp;</span>
          <span v-if="room.has_sound">音响</span>
          <span v-if="room.has_internet">&nbsp;</span>
          <span v-if="room.has_internet">网络</span>
        </p>
        <p>价格：{{ room.price_per_hour }}元/小时</p>
        <button @click="goToOrder(room)">立即预订</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from '../axios';
import { useRouter } from 'vue-router';
import { useAutoRefresh } from '../utils/useAutoRefresh';
import { useUserStore } from '../store/UserStore';
import { useWebSocketStore } from '../store/WebSocketStore';

const router = useRouter();
const userStore = useUserStore();

const search = ref({
  startTime: '',
  participantNum: 1,
  hasProjector: false,
  hasSound: false,
  hasInternet: false
});

const rooms = ref([]); // 存储会议室列表

const minDateTime = ref('');
const maxDateTime = ref('');

onMounted(() => {
  const now = new Date();
  const minDate = new Date(now.getTime());
  const maxDate = new Date(now.getTime() + 60 * 24 * 60 * 60 * 1000); // 最大 60 天后

  const formatDateTime = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:00`;
  };

  minDateTime.value = formatDateTime(minDate);
  maxDateTime.value = formatDateTime(maxDate);
});

const updateOrderStatus = (orderId, status) => {
  filterRooms(); // 刷新会议室列表，确保状态同步
};

const handleOrderUpdated = (payload) => {
  updateOrderStatus(payload.orderId, payload.status);
};

onMounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.on('server:order-updated', handleOrderUpdated);
});

onUnmounted(() => {
  const wsStore = useWebSocketStore();
  wsStore.off('server:order-updated', handleOrderUpdated);
});

// 辅助函数：支持“不限”逻辑
const matchesDevice = (roomVal, searchVal) => {
  return !searchVal || Boolean(roomVal) === searchVal;
};

onMounted(() => {
  filterRooms();
  useAutoRefresh(filterRooms, 2000); // 每2秒刷新一次
});

// 获取并过滤会议室
const filterRooms = async () => {
  try {
    const response = await axios.get('/rooms/list');
    const allRooms = response.data.data;
    // alert(JSON.stringify(allRooms));
    // rooms.value = allRooms;

    // 过滤逻辑
    rooms.value = allRooms.filter(room => {
      return (
        room.seat_count >= search.value.participantNum &&
        matchesDevice(room.has_projector, search.value.hasProjector) &&
        matchesDevice(room.has_sound, search.value.hasSound) &&
        matchesDevice(room.has_internet, search.value.hasInternet) &&
        room.status === '空闲'
      );
    });
  } catch (error) {
    console.error('获取会议室列表失败:', error);
    rooms.value = [];
  }
};

// 预订跳转并创建订单
const goToOrder = async (room) => {
  const { startTime, endTime, participantNum } = search.value;

  if (!startTime || !endTime || participantNum < 1) {
    alert('请先填写完整的预订信息');
    return;
  }

  const now = new Date();
  const startDateTime = new Date(startTime);
  const endDateTime = new Date(endTime);

  const maxDate = new Date(now.getTime() + 60 * 24 * 60 * 60 * 1000);

  // 校验是否在允许的时间范围内
  if (startDateTime > maxDate) {
    alert('最多可提前 60 天预约，您选择的日期已超过限制');
    return;
  }

  // 校验是否在每日 8:00 - 21:00 之间
  const startHour = startDateTime.getHours();
  const endHour = endDateTime.getHours();

  if (startHour < 8 || startHour >= 21 || endHour < 8 || endHour >= 21) {
    alert('会议室可用时间为每日 8:00 - 21:00，请选择有效时间段');
    return;
  }

  // 校验是否为整点
  if (startDateTime.getMinutes() !== 0 || endDateTime.getMinutes() !== 0) {
    alert('请选择整点时间（例如 09:00、10:00）');
    return;
  }

  // 校验开始时间是否早于结束时间
  if (startDateTime >= endDateTime) {
    alert('开始时间必须早于结束时间');
    return;
  }

  const orderData = {
    roomId: room.id,
    startTime,
    endTime,
    participantNum
  };

  try {
    const response = await axios.post('/orders/add', orderData);

    if (response.status === 201 || response.status === 200) {
      const orderId = response.data.data?.orderId || response.data.data?.id;

      router.push({
        path: '/confirm',
        query: {
          roomId: room.id,
          startTime,
          endTime,
          participantNum,
          orderId
        }
      });
    } else {
      alert(response.data.message || '创建订单失败');
    }
  } catch (error) {
    alert(error.response?.data?.message || '创建订单失败，请重试');
  }
};

// 初始化加载会议室列表
onMounted(() => {
  filterRooms();
});
</script>

<style scoped>
.header-panel {
  position: relative;
  width: 100%;
  max-width: 900px; /* 和 .booking-container 保持一致 */
  margin: 0 auto;
  text-align: center;
}

.my-btn {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #6b7280;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.my-btn:hover {
  background-color: #4b5563;
}

.booking-container {
    align-items: center;
}
.search-panel {
  /* margin-bottom: 20px; */
  margin: 0 auto;
  display: grid;
  gap: 10px;
  max-width: 225px;
}
.device-check {
  display: flex;
  gap: 10px;
  align-items: center;
}
.room-list {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}
.room-card {
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}
button {
  background-color: #3b82f6;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>